package com.tm.service.impl;

import com.alibaba.cloud.commons.io.FileUtils;
import com.alibaba.fastjson.JSON;
import com.tm.mapper.HomePageMapper;
import com.tm.pojo.ProvincePojo;
import com.tm.pojo.bo.ShopBo;
import com.tm.pojo.dto.UserPositionDto;
import com.tm.pojo.vo.*;
import com.tm.result.Result;
import com.tm.service.HomePageService;
import com.tm.utils.CalculateDistanceUtil;
import com.tm.utils.ConvertLatLngIntoRegion;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiaobai
 * @create 2022-12-16 20:47
 */
@Service
public class HomePageServiceImpl implements HomePageService {

    @Autowired
    private HomePageMapper homePageMapper;


    private static Map<Integer,String>  textTypeMap= new HashMap();
    private static Map<Integer,String>  userJobMap= new HashMap();
    static {
        textTypeMap.put(1,"人体曲线");
        textTypeMap.put(2,"养生护理");
        textTypeMap.put(3,"产品推荐");
        userJobMap.put(0,"时尚辣妈");
        userJobMap.put(1,"美妆博主");
        userJobMap.put(2,"精准女人");
        userJobMap.put(3,"家庭主妇");
    }

    //精选活动
    @Override
    public Result selectedActivities() {

        List<SelectedActivitiesVo> selectedActivitiesVoList = homePageMapper.selectedActivities();

        return Result.SUCCESS(selectedActivitiesVoList);
    }

    //每日必选
    @Override
    public Result dailyRequired(Integer userAge) {


        List<DailyRequiredVo> dailyRequiredVoList = homePageMapper.dailyRequired(userAge);

        return Result.SUCCESS(dailyRequiredVoList);
    }

    //看视频
    @Override
    public Result homeVideo(Integer pageNow, Integer pageSize) {

        //计算起始下标
        Integer startIndex = (pageNow - 1) * pageSize;


        List<VideoVo> videoVoList = homePageMapper.homeVideo(startIndex,pageSize);
        return Result.SUCCESS(videoVoList);
    }

    //有好货
    @Override
    public Result haveNiceGoods() {


        List<RecommendGoodsVo>   RecommendGoodsVoList =  homePageMapper.haveNiceGoods();
        return Result.SUCCESS(RecommendGoodsVoList);
    }

    @Override
    public Result  beautifulInstitute(Long userId, Long dateTime) {

        Long statTime =  dateTime - 86400000;
        Long endTime  =  dateTime + 86400000 ;
        List<TextVo> textVoList = null;
        if(userId != null){
            textVoList =  homePageMapper.userFollowText(userId,statTime,endTime);
            List<TextVo> unFollowTextList =  homePageMapper.unUserFollowText(userId,statTime,endTime);
            textVoList.addAll(unFollowTextList);
        }else {
            textVoList=   homePageMapper.beautifulInstitute(statTime , endTime);

        }
        textVoList.forEach(a ->{
            a.setTextType(textTypeMap.get(a.getTextTypeId()));
            a.setUserJob(userJobMap.get(a.getUserJobId()));
        });

        return Result.SUCCESS(textVoList);
    }

    //查询附近店铺并晒选
    @Override
    public Result nearShop(UserPositionDto userPositionDto) {
        List<ShopBo> shopBos= null;
        //判断有无用户位置信息
        if(StringUtils.isBlank(userPositionDto.getLongitude()) && StringUtils.isBlank(userPositionDto.getLatitude()) ){

             shopBos =  homePageMapper.selectNearShop(110000,110100,userPositionDto.getUserId());
        }else {
            List<ProvincePojo> provincePojoList = areaInfo();
            String area = ConvertLatLngIntoRegion.inverseGeocoding(userPositionDto.getLongitude(),userPositionDto.getLatitude());
            String[] split = area.split(",");
            // 市
            String province = split[0];
            // 区
            String city = split[1];

            provincePojoList.forEach(a->{
                if(a.getProvinceName().equals(province)){
                    userPositionDto.setProvinceId(a.getProvinceCode());

                    a.getCities().forEach(b->{
                        if(b.getCityName().equals(city)){
                            userPositionDto.setCityId(b.getCityCode());
                        }
                    });
                }
            });
                shopBos =  homePageMapper.selectNearShop(userPositionDto.getProvinceId(),userPositionDto.getCityId(),userPositionDto.getUserId());

        }



        //没有条件查询 按照用户光临过的店铺排
        if(userPositionDto.getBusinessId() == null && userPositionDto.getSearchType() == null){

            List<ShopBo> collect = shopBos.stream().sorted(Comparator.comparing(ShopBo::getUserPresence).reversed())
                    .collect(Collectors.toList());
            return Result.SUCCESS(collect);
        }
        // 商家
        List<ShopBo> shopBosList = null;
        if(userPositionDto.getBusinessId() != null && userPositionDto.getSearchType() == null){
            List<ShopBo> shopBosList2 =new ArrayList();
            shopBos.forEach(a->{
                if(a.getBusinessId().equals(userPositionDto.getBusinessId())){
                    shopBosList2.add(a);
                }
            });
           return Result.SUCCESS(shopBosList2);
        }
        if(userPositionDto.getBusinessId() == null && userPositionDto.getSearchType() != null){
            shopBosList = shopBos;
        }
        if(userPositionDto.getBusinessId() != null && userPositionDto.getSearchType() != null){
            List<ShopBo> shopBosList2 =new ArrayList();
            shopBos.forEach(a->{
                if(a.getBusinessId().equals(userPositionDto.getBusinessId())){
                    shopBosList2.add(a);
                }
            });
            shopBosList = shopBosList2;
        }

        // 条件查询商家
        List<ShopVo> shopVoList1 = null;
        switch (userPositionDto.getSearchType()){
            // 智能筛选
            case 1:
                List<ShopBo> collect1 = shopBosList.stream().sorted(Comparator.comparing(ShopBo::getUserPresence).reversed())
                        .collect(Collectors.toList());
                shopVoList1 = boToVo(collect1);
                break;
            //离我最近
            case 2:
                //调用计算距离的工具类
                CalculateDistanceUtil calculateDistanceUtil = new CalculateDistanceUtil();
                shopBosList.forEach(a->{
                    double v = calculateDistanceUtil.GetDistance(Double.valueOf(userPositionDto.getLongitude()),
                            Double.valueOf(userPositionDto.getLatitude()),
                            Double.valueOf(a.getLatitude()),
                            Double.valueOf(a.getLatitude()));
                    a.setUserDistance((long) v);
                });
                List<ShopBo> collect2 = shopBosList.stream().sorted(Comparator.comparing(ShopBo::getUserDistance)).collect(Collectors.toList());
                shopVoList1 = boToVo(collect2);
                break;
            //评分最高
            case 3:
                List<ShopBo> collect3 = shopBosList.stream().sorted(Comparator.comparing(ShopBo::getEvaluationGrade).reversed()).collect(Collectors.toList());
                shopVoList1 = boToVo(collect3);
                break;
            //最受欢迎
            case 4:
                List<ShopBo> collect4 = shopBosList.stream().sorted(Comparator.comparing(ShopBo::getCommentCount).reversed())
                        .collect(Collectors.toList());
                shopVoList1 = boToVo(collect4);
                break;
           }

        return Result.SUCCESS(shopVoList1);
    }


    //讲bo转换成Vo
    private static List<ShopVo> boToVo(List <ShopBo> list){
        List<ShopVo> shopVoList = new ArrayList<>();
        list.forEach(a->{
            ShopVo.Builder builder = new ShopVo.Builder();
            builder.shopId(a.getShopId())
                    .shopName(a.getShopName())
                    .shopPhone(a.getShopPhone())
                    .shopImg(a.getShopImg())
                    .shopAddressStr(a.getShopAddressStr())
                    .evaluationGrade(a.getEvaluationGrade())
                    .userDistance(a.getUserDistance())
                    .userPresence(a.getUserPresence())
                    .commentCount(a.getCommentCount());
            shopVoList.add(builder.build());
        });
        return shopVoList;
    }

    //使用地区json文件
    private static List<ProvincePojo> areaInfo(){

        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:city.json");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        String json = null;
        try {
            json = FileUtils.readFileToString(file, "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<ProvincePojo> provincePojoList = JSON.parseArray(json, ProvincePojo.class);
        return provincePojoList;
    }


}
